<template>
  <el-tabs type="border-card" class="content-tabs">
    <el-tab-pane label="会议室管理">
      <el-card class="content-card">
        <template #header>
          <div class="card-header">
            <span>会议室管理</span>
          </div>
        </template>

        <div class="search-form">
          <span>房间名：</span>
          <el-input v-model="selectValue.roomName" placeholder="请输入房间名"></el-input>
          <span>房间面积(平米)：</span>
          <el-input v-model.number="selectValue.roomSquare" placeholder="请输入房间面积"></el-input>
          <span>房间容量(座)：</span>
          <el-input v-model.number="selectValue.roomCapacity" placeholder="请输入房间容量"></el-input>

          <el-checkbox v-model="selectValue.roomProjector" label="投影仪"></el-checkbox>
          <el-checkbox v-model="selectValue.roomAudio" label="音响"></el-checkbox>
          <el-checkbox v-model="selectValue.roomNetwork" label="网络"></el-checkbox>

          <span>房间类型：</span>
          <el-select v-model="selectValue.roomType" placeholder="全部(空)">
            <el-option
            v-for="item in option0"
            :key="item.id"
            :label="item.label"
            :value="item.value"
            />
          </el-select>
          <span>房间状态：</span>
          <el-select v-model="selectValue.roomStatus" placeholder="全部(空)">
            <el-option
            v-for="item in option1"
            :key="item.id"
            :label="item.label"
            :value="item.value"
            />
          </el-select>
          <span>价格(元/小时)：</span>
          <el-input v-model.number="selectValue.roomPrice" placeholder="请输入房间价格"></el-input>
          <el-button type="primary" @click="fetchRoomList()">搜索</el-button>
          <el-button type="success" @click="openAddDialog()">+ 新增</el-button>          
        </div>

        <div class="content-box">
          <el-table
            :data="roomList"
            style="width: 100%; margin-top: 20px"
            stripe
            row-key="roomId"
          >
            <el-table-column
              type="index"
              width="80"
            />
            <el-table-column
              prop="roomName"
              label="房间名"
              show-overflow-tooltip
            />
            <el-table-column
              prop="roomType"
              label="类型"
            />            
            <el-table-column
              prop="roomSquare"
              label="面积/平米"
              width="160"
            />
            <el-table-column
              prop="roomCapacity"
              label="容量/座"
              width="160"
            />
            <el-table-column
              prop="roomPrice"
              label="价格(元/小时)"
              width="160"
            />
            <el-table-column
              prop="roomProjector"
              label="投影设备"
              :formatter="formatBoolean"
              width="80"
            />
            <el-table-column
              prop="roomAudio"
              label="音响"
              :formatter="formatBoolean"
              width="80"
            />
            <el-table-column
              prop="roomNetwork"
              label="网络"
              :formatter="formatBoolean"
              width="80"
            />
            <el-table-column
              prop="roomStatus"
              label="状态"
              width="80"
            />
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="openEditDialog(scope.row)"
                >
                  修改
                </el-button>
                <el-button
                  type="warning"
                  size="small"
                  @click="deleteRoom(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            :total="total"
            current-page="currentPage"
            :page-size="8"
            :pager-count="8"
            layout="total, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
            class="pagination-container"
          />
        </div>
      </el-card>
    </el-tab-pane>
    <el-dialog 
      v-model="isAdd"
      title="新增房间"
      align-center
      width="500px"
      :close-on-click-modal="false"
      :before-close="closeAddDialog"
    >
      <template #default>
        <el-form ref="addRef" :model="addValue" :rules="addRules">
          <el-form-item label="房间名:&nbsp&nbsp&nbsp&nbsp" prop="roomName">
            <el-input v-model="addValue.roomName" placeholder="请输入房间名"></el-input>
          </el-form-item>
          <el-form-item label="房间类型:" prop="roomType">
            <el-select v-model="addValue.roomType" placeholder="全部(空)">
              <el-option
                v-for="item in option0"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="房间面积:" prop="roomSquare">
            <el-input v-model.number="addValue.roomSquare" placeholder="请输入房间面积"></el-input>
          </el-form-item>
          <el-form-item label="房间容量:" prop="roomCapacity">
            <el-input v-model.number="addValue.roomCapacity" placeholder="请输入房间容量"></el-input>
          </el-form-item>
          <el-form-item label="房间投影:" prop="roomProjector">
            <el-checkbox v-model="addValue.roomProjector" label="投影仪"></el-checkbox>
          </el-form-item>
          <el-form-item label="房间音响:" prop="roomAudio">
            <el-checkbox v-model="addValue.roomAudio" label="音响"></el-checkbox>
          </el-form-item>
          <el-form-item label="房间网络:" prop="roomNetwork">
            <el-checkbox v-model="addValue.roomNetwork" label="网络"></el-checkbox>
          </el-form-item>
          <el-form-item label="房间价格:" prop="roomPrice">
            <el-input v-model.number="addValue.roomPrice" placeholder="请输入房间价格"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
          <div class="dialog-footer">
              <el-button class="cancel-btn" @click="closeAddDialog()">取消新增</el-button>
              <el-button class="submit-btn" type="primary" @click="submitAddDialog()">
                提交新增
              </el-button>
          </div>
      </template>
    </el-dialog>
    <el-dialog 
      v-model="isEdit"
      title="修改房间信息"
      align-center
      width="500px"
      :close-on-click-modal="false"
      :before-close="closeEditDialog"
    >
      <template #default>
        <el-form ref="editRef" :model="editValue" :rules="editRules">
          <el-form-item label="房间名:&nbsp&nbsp&nbsp&nbsp" prop="roomName">
            <el-input v-model="editValue.roomName" placeholder="请输入房间名"></el-input>
          </el-form-item>
          <el-form-item label="房间类型:" prop="roomType">
            <el-select v-model="editValue.roomType" placeholder="全部(空)">
              <el-option
                v-for="item in option0"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="房间面积:" prop="roomSquare">
            <el-input v-model.number="editValue.roomSquare" placeholder="请输入房间面积"></el-input>
          </el-form-item>
          <el-form-item label="房间容量:" prop="roomCapacity">
            <el-input v-model.number="editValue.roomCapacity" placeholder="请输入房间容量"></el-input>
          </el-form-item>
          <el-form-item label="房间投影:" prop="roomProjector">
            <el-checkbox v-model="editValue.roomProjector" label="投影仪"></el-checkbox>
          </el-form-item>
          <el-form-item label="房间音响:" prop="roomAudio">
            <el-checkbox v-model="editValue.roomAudio" label="音响"></el-checkbox>
          </el-form-item>
          <el-form-item label="房间网络:" prop="roomNetwork">
            <el-checkbox v-model="editValue.roomNetwork" label="网络"></el-checkbox>
          </el-form-item>
          <el-form-item label="房间价格:" prop="roomPrice">
            <el-input v-model.number="editValue.roomPrice" placeholder="请输入房间价格"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
          <div class="dialog-footer">
              <el-button class="cancel-btn" @click="closeEditDialog()">取消修改</el-button>
              <el-button class="submit-btn" type="primary" @click="submitEditDialog()">
                提交修改
              </el-button>
          </div>
      </template>
    </el-dialog>
  </el-tabs>
</template>

<script setup>
  import { ElMessage,ElMessageBox } from 'element-plus'
  import { ref,reactive,onMounted,nextTick } from 'vue'
  import {
    GetRoomListServer,
    GetRoomServer,
    AddNewRoomServer,
    EditRoomServer,
    DeleteRoomServer,
  } from '@/api/instance'

  onMounted(()=>{
    fetchRoomList();
  })
  const selectValue = reactive({
    roomName:"",
    roomType:"",
    roomSquare:null,
    roomCapacity:null,
    roomProjector:false,
    roomAudio:false,
    roomNetwork:false,
    roomPrice:null,
    roomStatus:'',
  })
  const addValue=reactive({
    roomName:"",
    roomType:"",
    roomSquare:null,
    roomCapacity:null,
    roomProjector:false,
    roomAudio:false,
    roomNetwork:false,
    roomPrice:null,
    roomStatus:'',
  })
  const editValue=reactive({
    roomId:0,
    roomName:"",
    roomType:"",
    roomSquare:null,
    roomCapacity:null,
    roomProjector:false,
    roomAudio:false,
    roomNetwork:false,
    roomPrice:null,
    roomStatus:'',
  })
  const addRef=ref(null)
  const editRef=ref(null)
  const isAdd=ref(false)
  const isEdit=ref(false)
  const addRules = {
    roomName: [
      { required: true, message: '请输入房间名', trigger: 'blur' },
      { min: 1, message: '房间名长度至少为1', trigger: 'blur' }
    ],
    roomType: [
      { required: true, message: '请选择房间类型', trigger: 'change' },
      { 
        validator: (rule, value) => value === '教室型' || value === '圆桌型',
        message: '请输入男或女',
        trigger: 'change'
      }
    ],
    roomSquare: [
      { required: true, message: '请输入房间面积', trigger: 'blur' },
      { type: 'number', message: '请输入数字', trigger: 'blur' , transform:(value) => Number(value)},
      { validator: (rule,value) => Number(value) > 0 ,
        message: '房间面积必须大于等于1',
        trigger:'blur'
      }
    ],
    roomCapacity: [
      { required: true, message: '请输入房间容量', trigger: 'blur' },
      { type: 'number', message: '请输入数字', trigger: 'blur' , transform:(value) => Number(value)},
      { validator: (rule,value) => Number(value) > 0 ,
        message: '房间容量必须大于等于1',
        trigger:'blur'
      }
    ],
    roomProjector: [
      { required: true, message: '请确认是否支持投影仪', trigger: 'change' }
    ],
    roomAudio: [
      { required: true, message: '请确认是否支持音响', trigger: 'change' }
    ],
    roomNetwork: [
      { required: true, message: '请确认是否支持网络', trigger: 'change' }
    ],
    roomPrice: [
      { required: true, message: '请输入房间价格', trigger: 'blur' },
      { type: 'number', message: '请输入数字', trigger: 'blur' , transform:(value) => Number(value)},
      { validator: (rule,value) => Number(value) > 0 ,
        message: '房间价格必须大于等于1',
        trigger:'blur'
      }
    ],
  };

  const editRules = {
    roomName: [
      { required: true, message: '请输入房间名', trigger: 'blur' },
      { min: 1, message: '房间名长度至少为1', trigger: 'blur' }
    ],
    roomType: [
      { required: true, message: '请选择房间类型', trigger: 'change' },
      { 
        validator: (rule, value) => value === '教室型' || value === '圆桌型',
        message: '请输入男或女',
        trigger: 'change'
      }
    ],
    roomSquare: [
      { required: true, message: '请输入房间面积', trigger: 'blur' },
      { type: 'number', message: '请输入数字', trigger: 'blur' , transform:(value) => Number(value)},
      { validator: (rule,value) => Number(value) > 0 ,
        message: '房间面积必须大于等于1',
        trigger:'blur'
      }
    ],
    roomCapacity: [
      { required: true, message: '请输入房间容量', trigger: 'blur' },
      { type: 'number', message: '请输入数字', trigger: 'blur' , transform:(value) => Number(value)},
      { validator: (rule,value) => Number(value) > 0 ,
        message: '房间容量必须大于等于1',
        trigger:'blur'
      }
    ],
    roomProjector: [
      { required: true, message: '请确认是否支持投影仪', trigger: 'change' }
    ],
    roomAudio: [
      { required: true, message: '请确认是否支持音响', trigger: 'change' }
    ],
    roomNetwork: [
      { required: true, message: '请确认是否支持网络', trigger: 'change' }
    ],
    roomPrice: [
      { required: true, message: '请输入房间价格', trigger: 'blur' },
      { type: 'number', message: '请输入数字', trigger: 'blur' , transform:(value) => Number(value)},
      { validator: (rule,value) => Number(value) > 0 ,
        message: '房间价格必须大于等于1',
        trigger:'blur'
      }
    ],
  }
  const option0=[
    { id:0 , value: '' ,label: '全部(空)' },
    { id:1 , value: '教室型' , label: '教室型' },
    { id:2 , value: '圆桌型' , label: '圆桌型' },
  ]
  const option1=[
    { id:0 , value: '' ,label: '全部(空)' },
    { id:1 , value: '维护' , label: '维护' },
    { id:2 , value: '使用' , label: '使用' },
    { id:3 , value: '预定' , label: '预定' },
    { id:4 , value: '空闲' , label: '空闲' },
  ]
  const roomList=reactive([
  ])
  const formatBoolean = (row, column, cellValue) =>{
    var ret = ''  //你想在页面展示的值
    if (cellValue) {
        ret = "支持"  //根据自己的需求设定
    } else {
        ret = "不支持"
    }
    return ret
  }
  const currentPage = ref(1)
  const total=ref(0)
  const fetchRoomList=async (page=1) => {
    currentPage.value=page;
    if (typeof selectValue.roomSquare !== 'number' && selectValue.roomSquare !== null && selectValue.roomSquare !== '') {
      ElMessage.error('房间面积输入格式不对')
      return
    }
    if (typeof selectValue.roomCapacity !== 'number' && selectValue.roomCapacity !== null && selectValue.roomCapacity !== '') {
      ElMessage.error('房间容量输入格式不对')
      return
    }
    if (typeof selectValue.roomPrice !== 'number' && selectValue.roomPrice !== null && selectValue.roomPrice !== '') {
      ElMessage.error('房间价格输入格式不对')
      return
    }
    try{
      const res = await GetRoomListServer({
        roomName:selectValue.roomName,
        roomType:selectValue.roomType,
        roomSquare:selectValue.roomSquare,
        roomCapacity:selectValue.roomCapacity,
        roomProjector:selectValue.roomProjector,
        roomAudio:selectValue.roomAudio,
        roomNetwork:selectValue.roomNetwork,
        roomPrice:selectValue.roomPrice,
        roomStatus:selectValue.roomStatus,
      });
      if(res.code===0){
        const allData=res.data||[];
        total.value=allData.length;
        const start=(page-1)*8;
        const end=start+8;
        roomList.splice(0,roomList.length,...allData.slice(start,end));
      }else{
        ElMessage.error(res.message || '获取会议室列表失败')  
      }
    }catch(error){
      ElMessage.error(error.message || '网络请求失败1')
    }
  }
  const deleteRoom =async (row) => {
    ElMessageBox.confirm('确定要删除该房间吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async() => {
      try{
        const res = await DeleteRoomServer({
          roomId:row.roomId,
        })
        if(res.code===0){
          ElMessage.success('房间删除成功')
          fetchRoomList(currentPage.value);
        }else{
          ElMessage.error(res.message || '房间删除失败')
        }
      }catch(error){
        ElMessage.error(error.message || '网络请求失败2')
      }
    })
  }
  const openAddDialog = () => {
    // addValue.roomName=''
    // addValue.roomType=''
    // addValue.roomSquare=null
    // addValue.roomCapacity=null
    // addValue.roomProjector=false
    // addValue.roomAudio=false
    // addValue.roomNetwork=false
    // addValue.roomPrice=null
    // addValue.roomStatus=''//清空
    isAdd.value=true
  }
  const submitAddDialog =async () => {
    try{
      await addRef.value.validate();
      try{
        const res = await AddNewRoomServer({
          roomName:addValue.roomName,
          roomType:addValue.roomType,
          roomSquare:addValue.roomSquare,
          roomCapacity:addValue.roomCapacity,
          roomProjector:addValue.roomProjector,
          roomAudio:addValue.roomAudio,
          roomNetwork:addValue.roomNetwork,
          roomPrice:addValue.roomPrice,
        })
        if(res.code===0){
          ElMessage.success('新增房间成功')
          fetchRoomList(currentPage.value);
          isAdd.value=false
          nextTick(()=>{
            addRef.value?.resetFields()//需要清空
          })
        }else{
          ElMessage.error(res.message || '新增房间失败')
        }
      }catch(error){
        ElMessage.error(error.message || '网络请求失败3')
      }
    }catch(err){
      ElMessage.error(err.message || '输入格式出错1')
    }
  }
  const closeAddDialog = () => {
    // addValue.roomName=''
    // addValue.roomType=''
    // addValue.roomSquare=null
    // addValue.roomCapacity=null
    // addValue.roomProjector=false
    // addValue.roomAudio=false
    // addValue.roomNetwork=false
    // addValue.roomPrice=null
    // addValue.roomStatus=''//清空
    isAdd.value=false
    nextTick(()=>{
      addRef.value?.resetFields()
    })
  }
  const openEditDialog = async (row) => { 
    try{
      const res = await GetRoomServer({
        roomId:row.roomId
      })
      if(res.code===0){
        Object.assign(editValue,res.data)
        isEdit.value=true
      }else{
        ElMessage.error(res.message || '获取修改信息失败')
      }
    }catch(error){
      ElMessage.error(error.message || '网络请求失败4')
    }
  }
  const submitEditDialog =async () => {
    try{
      await editRef.value.validate();
      try{
        const res = await EditRoomServer({
          roomId:editValue.roomId,
          roomName:editValue.roomName,
          roomType:editValue.roomType,
          roomSquare:editValue.roomSquare,
          roomCapacity:editValue.roomCapacity,
          roomProjector:editValue.roomProjector,
          roomAudio:editValue.roomAudio,
          roomNetwork:editValue.roomNetwork,
          roomPrice:editValue.roomPrice,
        })
        if(res.code===0){
          ElMessage.success('房间修改成功')
          fetchRoomList(currentPage.value);
          isEdit.value=false;
        }else{
          ElMessage.error(res.message || '房间修改失败')
        }
      }catch(error){
        ElMessage.error(error.message || '网络请求失败5')
      }
    }catch(err){
      ElMessage.error(err.message || '输入格式出错2')
    }
  }
  const closeEditDialog = () => {
    isEdit.value=false 
    nextTick(()=>{
      editRef.value?.resetFields()
    })
  }
  // 处理每页显示条目数变化
  const handleSizeChange = (pageSize) => {
    // 可以在这里添加逻辑来处理每页显示条目数的变化
      console.log(`每页显示条目数变为: ${pageSize}`);
  };
  // 处理已创建社团分页变化
  const handlePageChange = (newPage) => {
      fetchRoomList(newPage);
  };
</script>

<style lang="scss" scoped>
  .content-tabs{
    height: 95%;
    width: 95%;
    margin: 15px auto;//原来为20px，现在为15px
    .content-card{
      height: 95%;
      margin: 20px;
      .card-header{
        font-size: 18px;
        font-weight: bold;
      }
      .search-form{
        display: flex;
        justify-content: flex-start;
        flex-direction: row;
        flex-wrap: wrap;
        align-items: center;
        gap: 10px;
        margin-bottom: 15px;
        :deep(.el-select){
          width: 200px;
          margin-right: 20px;
        }
        :deep(.el-input){
          width: 200px;
          margin-right: 20px;
        }
        :deep(.el-checkbox){
          margin-right: 20px;
          .el-checkbox__label{
            font-size: 16px;
          }
        }
      }
      .content-box{
        .pagination-container{
          display: flex;
          justify-content: center;
          margin-top: 30px
        }
      }
    }
  }
  .el-tab-pane {
    height:100%;
  }
  .el-form {
    padding: 5px;
  }
  .el-form-item {
    margin-bottom: 25px; /* 原默认值为 25px，可调大数值 */
    margin-right: 35%;
  }
</style>